package com.woniu.zsd.platform.Netty;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

public class NettyServer {

    private final int port;

    public NettyServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        // 配置 Netty 的线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // HTTP 编解码器
                            pipeline.addLast(new HttpServerCodec());
                            // 将 HTTP 消息聚合为 FullHttpRequest/FullHttpResponse
                            pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                            // WebSocket 协议处理，指定访问路径为 "/websocket"
                            pipeline.addLast(new WebSocketServerProtocolHandler("/websocket"));
                            // 自定义业务处理器
                            pipeline.addLast(new WebSocketFrameHandler());
                        }
                    });

            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("Netty 服务启动成功，监听端口：" + port);
            System.out.println("Netty 服务启动成功，绑定地址：" + future.channel().localAddress());

            // 阻塞等待，直到服务通道关闭
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
